<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="模型名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="模型标识" name="model">
          <t-input v-model:value="params.model" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="模型平台" name="platform">
          <t-select
            v-model:value="params.platform"
            :options="dictionaryStore.get('ai_platform')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="状态" name="status">
          <t-select
            v-model:value="params.status"
            :options="dictionaryStore.get('common_status')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="chatModelCRUD.page"
      column-controller-key="chatModelList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button @click="handleOpenDialog('create', { status: 0 })"> 新建模型 </t-button>
        </div>
      </template>
      <template #keyId="{ row }">
        {{ apiKeySimpleList.find((item) => item.id === row.keyId)?.name }}
      </template>
      <template #status="{ row }">
        <t-switch
          v-model:value="row.status"
          :custom-value="[0, 1]"
          :loading="row.loading"
          @change="handleChangeStatus(row)"
        />
      </template>
      <template #isUse="{ row }">
        <t-switch
          v-model:value="row.isUse"
          :custom-value="['1', '0']"
          :loading="row.loading"
          @change="handleChangeIsUse(row)"
        />
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link theme="primary" @click="handleOpenDialog('read', { id: row.id })"> 详情 </t-link>
          <t-link theme="primary" @click="handleOpenDialog('update', { id: row.id })"> 编辑 </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="chatModelCRUD"
      header="*模型"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="模型平台" name="platform" :rules="[{ required: true, message: '请选择模型平台' }]">
        <t-select
          v-model:value="formData.platform"
          :options="dictionaryStore.get('ai_platform', 'number')"
          placeholder="请选择模型平台"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.platform = null"
        />
      </t-form-item>
      <t-form-item label="API密钥" name="keyId" :rules="[{ required: true, message: '请选择API密钥' }]">
        <t-select
          v-model:value="formData.keyId"
          :options="apiKeySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          placeholder="请选择API密钥"
          clearable
          filterable
          :readonly="readonly"
          @clear="formData.keyId = null"
        />
      </t-form-item>
      <t-form-item label="模型名称" name="name" :rules="[{ required: true, message: '请输入模型名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入模型名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="模型标识" name="model" :rules="[{ required: true, message: '请输入模型标识' }]">
        <t-input v-model:value="formData.model" placeholder="请输入模型标识" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="显示顺序" name="sort" :rules="[{ required: true, message: '请输入显示顺序' }]">
        <t-input-number
          v-model:value="formData.sort"
          placeholder="请输入显示顺序"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="状态" name="status" :rules="[{ required: true, message: '请选择状态' }]">
        <t-radio-group v-model:value="formData.status">
          <t-radio
            v-for="_ in dictionaryStore.get('common_status', 'number')"
            :key="_.value"
            :value="_.value"
            :readonly="readonly"
          >
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="温度参数" name="temperature">
        <t-input-number
          v-model:value="formData.temperature"
          placeholder="请输入温度参数"
          :min="0"
          :max="2"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="回复token数" name="maxTokens">
        <t-input-number
          v-model:value="formData.maxTokens"
          placeholder="请输入回复token数"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
      <t-form-item label="上下文数量" name="maxContexts">
        <t-input-number
          v-model:value="formData.maxContexts"
          placeholder="请输入上下文数量"
          :min="0"
          :allow-input-over-limit="false"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'ChatModel',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef } from 'vue';

import { getApiKeySimpleList } from '@/api/ai/api-key';
import { chatModelCRUD, enableConfig } from '@/api/ai/chat-model';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// api密钥精简列表
const apiKeySimpleList = ref([]);
// 处理获取api密钥精简列表
const handleGetApiKeySimpleList = () => {
  getApiKeySimpleList()
    .then((data) => {
      apiKeySimpleList.value = data;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetApiKeySimpleList();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '模型ID' },
  { colKey: 'name', title: '模型名称' },
  { colKey: 'model', title: '模型标识' },
  { colKey: 'keyId', title: 'API密钥' },
  { colKey: 'sort', title: '显示顺序 ' },
  { colKey: 'status', title: '状态' },
  { colKey: 'temperature', title: '温度参数' },
  { colKey: 'maxTokens', title: '回复token数' },
  { colKey: 'maxContexts', title: '上下文数量' },
  { colKey: 'isUse', title: '主配置' },
  { colKey: 'createTime', title: '创建时间' },
  { colKey: 'operation', title: '操作', width: 150 },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  chatModelCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理改变状态
const handleChangeStatus = (row: Record<string, any>) => {
  row.loading = true;
  const params = { ...row };
  chatModelCRUD
    .update(params)
    .then(() => {
      MessagePlugin.success('编辑成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      row.loading = false;
    });
};
// 处理改变主配置
const handleChangeIsUse = (row: Record<string, any>) => {
  row.loading = true;
  const params = { ...row };
  enableConfig(params)
    .then(() => {
      MessagePlugin.success('编辑成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      row.loading = false;
    });
};
</script>
